package skills.jssvc.deu.cn.skillsecond.programming1;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

import skills.jssvc.deu.cn.skillsecond.MyApplication;
import skills.jssvc.deu.cn.skillsecond.R;
import skills.jssvc.deu.cn.skillsecond.bean.Balance;
import skills.jssvc.deu.cn.skillsecond.util.HttpRequest;
import skills.jssvc.deu.cn.skillsecond.util.SqlHelper;


public class MyAccount3 extends Fragment {
    private final String TAG = "MyAccount3";
    private View view;
    private TextView balanceTv;
    private Spinner carSpinner;
    private EditText amountEt;
    private Button queryBtn,okBtn;

    private SqlHelper helper;
    private SQLiteDatabase db;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_myaccount3, container, false);
        initView();
        setListeners();
        return view;
    }

    private void initView(){
        balanceTv = (TextView)view.findViewById(R.id.frag1_myaccount3_balance_tv);
        carSpinner = (Spinner) view.findViewById(R.id.frag1_myaccount3_car_spinner);
        amountEt = (EditText) view.findViewById(R.id.frag1_myaccount3_amount_et);
        queryBtn = (Button) view.findViewById(R.id.frag1_myaccount3_query_btn);
        okBtn = (Button) view.findViewById(R.id.frag1_myaccount3_ok_btn);
    }

    private void setListeners(){
        queryBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                queryBalance(carSpinner.getSelectedItemPosition()+1);
            }
        });
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String money = amountEt.getText().toString().trim();
                if(!money.equals("")){
                    upBalance(carSpinner.getSelectedItemPosition()+1,Integer.valueOf(money));
                }

            }
        });
    }

    private void queryBalance(int car){
        String param = "{\"CarId\":"+String.valueOf(car)+", \"UserName\":\"user1\"}";
        HttpRequest.post("GetCarAccountBalance", param, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Balance balance = new Gson().fromJson(jsonObject.toString(), Balance.class);
                balanceTv.setText(String.valueOf(balance.getBalance()+"元"));
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(MyApplication.appContext,"查询请求出错！",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void upBalance(final int car, final int money){
        String param = "{\"CarId\":"+String.valueOf(car)+",\"Money\":"+String.valueOf(money)+", \"UserName\":\"user1\"}";
        HttpRequest.post("SetCarAccountRecharge", param, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    if(jsonObject.getString("RESULT").equals("S")){
                        Toast.makeText(MyApplication.appContext,"充值成功！",Toast.LENGTH_SHORT).show();
                        upRecord(car, money);
                        queryBalance(car);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(MyApplication.appContext,"充值出错！",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void upRecord(int car,int money){
        helper = new SqlHelper(MyApplication.appContext, SqlHelper.DA_NAME, null, 1);
        db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("carId",car);
        values.put("amount",money);
        values.put("time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
        values.put("user","user1");
        db.insert(SqlHelper.table_top, null, values);

        Cursor cursor = db.query(SqlHelper.table_top, null, null, null, null, null, null);
        if(cursor.moveToFirst()){
            do{
                Log.d(TAG, "upRecord: cursor id= "+cursor.getInt(cursor.getColumnIndex("id"))+"\n" +
                        "car="+cursor.getInt(cursor.getColumnIndex("carId"))+"\n" +
                        "amount=" +cursor.getInt(cursor.getColumnIndex("amount"))+"\n" +
                        "time=" +cursor.getString(cursor.getColumnIndex("time"))+"\n" +
                        "user=" +cursor.getString(cursor.getColumnIndex("user"))
                );
            }while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
    }



}
